<template>
  <div class="page-container">
    <div class="container">
    <!-- 标题部分 -->
    <h1 class="table-title">{{ tableTitle }}</h1>
    <!-- 切换按钮 -->
    <div class="toggle-buttons">
      <el-button
          type="primary"
          :plain="activeTab !== 'applications'"
          @click="switchTab('applications')"
      >
        我的申请历史
      </el-button>
      <el-button
          type="primary"
          :plain="activeTab !== 'salaries'"
          @click="switchTab('salaries')"
      >
        我的工资历史
      </el-button>
    </div>

    <!-- 表格部分 -->
    <el-table
        class="common-table"
        v-if="activeTab === 'applications'"
        :data="salaryRequests"
        border
        stripe
    >
      <el-table-column prop="id" label="审批记录ID" align="center" min-width="120" />
      <el-table-column prop="employeeName" label="员工姓名" align="center" min-width="120" />
      <el-table-column prop="baseSalary" label="基本工资（元）" align="center" min-width="120" />
      <el-table-column prop="bonusSalary" label="奖金（元）" align="center" min-width="120" />
      <el-table-column prop="salaryDeduction" label="扣款（元）" align="center" min-width="120" />
      <el-table-column prop="netSalary" label="净工资（元）" align="center" min-width="120" />
      <!-- 审批状态列 -->
      <el-table-column label="审批状态" align="center" min-width="150">
        <template #default="{ row }">
          <el-tag
              :type="getTagType(row.approvalStatus)"
              effect="dark"
          >
            {{ row.approvalStatus }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <el-table
        class="common-table"
        v-if="activeTab === 'salaries'"
        :data="salaryHistories"
        border
        stripe
    >
      <el-table-column prop="id" label="记录ID" align="center" min-width="120" />
      <el-table-column prop="baseSalary" label="基本工资（元）" align="center" min-width="120" />
      <el-table-column prop="bonusSalary" label="奖金（元）" align="center" min-width="120" />
      <el-table-column prop="salaryDeduction" label="扣款（元）" align="center" min-width="120" />
      <el-table-column prop="netSalary" label="净工资（元）" align="center" min-width="120" />
      <el-table-column prop="paymentDate" label="支付日期" align="center" min-width="150">
        <template #default="{ row }">
          {{ formatDate(row.paymentDate) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :total="activeTab === 'applications' ? totalRecords || 1 : salaryTotalRecords || 1"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
    />
  </div>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 当前激活的标签，默认为申请历史
const activeTab = ref('applications')

// 数据
const salaryRequests = ref([]) // 工资审批记录
const salaryHistories = ref([]) // 工资发放历史记录
const totalRecords = ref(0) // 工资审批记录总数
const salaryTotalRecords = ref(0) // 工资历史记录总数
const pageNum = ref(1) // 当前页码
const pageSize = ref(10) // 每页显示的记录数

// 计算标题
const tableTitle = computed(() =>
    activeTab.value === 'applications' ? '工资审批历史记录' : '工资发放历史'
)

// 获取用户信息
const getUserInfo = () => {
  try {
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    return userInfo?.employeeId || null
  } catch (error) {
    console.error('获取用户信息失败', error)
    return null
  }
}

// 获取工资审批记录
const fetchApplications = async () => {
  try {
    const response = await axios.get('http://localhost:8080/HR/getApproveSalary', {
      params: {
        employeeId: getUserInfo(),
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      salaryRequests.value = response.data.data.records
      totalRecords.value = response.data.data.total
    } else {
      ElMessage.error('获取工资审批记录失败: ' + response.data.message)
    }
  } catch (error) {
    ElMessage.error('请求失败，请稍后再试！')
    console.error('请求失败', error)
  }
}

// 获取工资历史记录
const fetchSalaries = async () => {
  try {
    const response = await axios.get('http://localhost:8080/HR/getSalaries', {
      params: {
        employeeId: getUserInfo(),
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      salaryHistories.value = response.data.data.records
      salaryTotalRecords.value = response.data.data.total
    } else {
      ElMessage.error('获取工资历史记录失败: ' + response.data.message)
    }
  } catch (error) {
    ElMessage.error('请求失败，请稍后再试！')
    console.error('请求失败', error)
  }
}

// 标签切换
const switchTab = (tab) => {
  activeTab.value = tab
  pageNum.value = 1 // 切换标签时重置页码
  if (tab === 'applications' && salaryRequests.value.length === 0) {
    fetchApplications()
  } else if (tab === 'salaries' && salaryHistories.value.length === 0) {
    fetchSalaries()
  }
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
};
const getTagType = (status) => {
  switch (status) {
    case '已通过':
      return 'success';
    case '待审批':
      return 'warning';
    case '已拒绝':
      return 'danger';
    default:
      return 'info'; // 默认类型
  }
};
// 页码变化时重新加载数据
const handlePageChange = (newPageNum) => {
  pageNum.value = newPageNum
  if (activeTab.value === 'applications') {
    fetchApplications()
  } else {
    fetchSalaries()
  }
}

// 初始化时加载默认标签的数据
onMounted(() => {
  fetchApplications()
})
</script>
<style scoped>
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.toggle-buttons {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  gap: 10px;
}

.common-table {
  width: 100%;
  table-layout: fixed;
}

.table-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
